<script setup lang="ts">
import type { ItemType, MenuProps } from 'ant-design-vue';

import { computed, createVNode, h, onMounted, reactive, ref, watch } from 'vue';

import { ColPage, ColVerticalPage, useVbenModal } from '@vben/common-ui';
import {
  AntDesignCluster,
  AntDesignRelevance,
  AntDesignTable,
  MdiApps,
} from '@vben/icons';

import { Empty, message, Modal } from 'ant-design-vue';

import { genModelDelApi, genModelSyncModelApi } from '#/api/gen/model';
import {
  genModelClassifyDelApi,
  genModelClassifyQueryClassifyAndModelApi,
} from '#/api/gen/modelType';

import { getMenuItem, getTableHandle, getTypeHandle } from './designModel.data';
import ModelFieldsConfig from './modules/ModelFieldsConfig.vue';
import ModelFormModal from './modules/ModelFormModal.vue';
import TypeFormModal from './modules/TypeFormModal.vue';

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

const [TypeModal, typeModalApi] = useVbenModal({
  connectedComponent: TypeFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      queryClassifyModels();
    }
  },
});
const [ModelModal, modelModalApi] = useVbenModal({
  connectedComponent: ModelFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      queryClassifyModels();
    }
  },
});

const state = reactive({
  rootSubmenuKeys: ['system', 'online'],
  openKeys: [],
  selectedKeys: [],
});
const classifyModels = ref([]);
const menuLists: ItemType[] = reactive([]);

onMounted(async () => {
  await queryClassifyModels();
});
function openTypeModal(id) {
  typeModalApi.setData({
    id,
  });
  typeModalApi.open();
}
function addModel(item) {
  modelModalApi.setData({
    modelClassifyId: item?.id,
  });
  modelModalApi.open();
}
const handleMenuItemClick = async (key, val) => {
  if (key === 'edit') {
    openTypeModal(val?.id);
  } else if (key === 'del') {
    Modal.confirm({
      title: `确认删除「${val?.name}」模型数据吗?`,
      content: createVNode(
        'div',
        { style: 'color:red;' },
        '注: 请先删除分类下的所有模型!!!',
      ),
      async onOk() {
        const msg = await genModelClassifyDelApi(val?.id);
        message.success(msg);
        await queryClassifyModels();
      },
      class: 'test',
    });
  }
};
function childSyncFun(child) {
  Modal.confirm({
    title: `确认同步「${child?.modelName}」模型数据吗?`,
    content: createVNode(
      'div',
      { style: 'color:red;' },
      '注: 请先保存后同步模型,同步会丢失表中所有数据!!!',
    ),
    async onOk() {
      const msg = await genModelSyncModelApi({ modelId: child?.id });
      message.success(msg);
      await queryClassifyModels();
    },
    class: 'test',
  });
}
function childEditFun(child) {
  modelModalApi.setData({
    id: child?.id,
  });
  modelModalApi.open();
}
function childDelFun(child) {
  Modal.confirm({
    title: `确认删除「${child?.modelName}」模型数据吗?`,
    content: createVNode(
      'div',
      { style: 'color:red;' },
      '注: 只会做移除操作,不会删除数据库模型表信息!!!',
    ),
    async onOk() {
      const msg = await genModelDelApi(child?.id);
      message.success(msg);
      await queryClassifyModels();
      state.selectedKeys = [];
    },
    class: 'test',
  });
}
const menuListsComputed = computed(() => {
  return classifyModels.value.map((item) => {
    const label = getTypeHandle(
      item?.name,
      item,
      addModel,
      handleMenuItemClick,
    );
    const key = item?.code;
    const icon = () => h(MdiApps);
    let children = [];
    if (item?.models.length > 0) {
      children = item.models?.map((child) => {
        const childLabel = getTableHandle(
          child?.modelName,
          child,
          childSyncFun,
          childEditFun,
          childDelFun,
        );
        const childKey = child?.modelCode;
        let tempIcon = AntDesignTable;
        if (child?.modelCharacter === 'tree') {
          tempIcon = AntDesignCluster;
        } else if (child?.modelCharacter === 'attach') {
          tempIcon = AntDesignRelevance;
        } else {
          tempIcon = AntDesignTable;
        }
        const childIcon = () =>
          h(tempIcon, {
            style: {
              color: child?.modelSyncStatus === 0 ? '#87d068' : '',
            },
          });
        return getMenuItem(childLabel, childKey, childIcon);
      });
    }
    return getMenuItem(label, key, icon, children, null);
  });
});

async function queryClassifyModels() {
  classifyModels.value = await genModelClassifyQueryClassifyAndModelApi();
}

// 监听计算属性的变化并更新 menuLists
watch(
  menuListsComputed,
  (newVal) => {
    menuLists.length = 0;
    newVal.forEach((item) => {
      menuLists.push(item);
    });
  },
  { deep: true },
);

const handleClick: MenuProps['onClick'] = (e) => {
  state.selectedKeys[0] = e?.key;
};
const onOpenChange = (newOpenKeys) => {
  newOpenKeys.length > 0
    ? (state.openKeys = [newOpenKeys[newOpenKeys.length - 1]])
    : (state.openKeys = []);
};
</script>

<template>
  <ColPage
    v-bind="{
      resizable: true,
      splitLine: true,
      splitHandle: true,
      leftWidth: 18,
      leftMaxWidth: 18,
      leftMinWidth: 18,
      rightWidth: 82,
      rightMinWidth: 82,
      rightMaxWidth: 82,
    }"
    auto-content-height
  >
    <TypeModal class="w-[30%]" />
    <ModelModal class="w-[40%]" />
    <template #left>
      <div
        class="border-border bg-card mr-2 h-full rounded-[var(--radius)] border p-2"
      >
        <ColVerticalPage>
          <template #header>
            <div class="flex font-medium">
              <a-button size="small" class="mr-1" @click="openTypeModal()">
                分类
              </a-button>
              <a-input-search placeholder="模型名称或编码" size="small" />
            </div>
          </template>
          <a-menu
            mode="inline"
            :items="menuLists"
            v-model:selected-keys="state.selectedKeys"
            v-model:open-keys="state.openKeys"
            @click="handleClick"
            @open-change="onOpenChange"
          />
        </ColVerticalPage>
      </div>
    </template>
    <div
      class="border-border bg-card ml-2 h-full rounded-[var(--radius)] border"
    >
      <component
        v-if="state.selectedKeys.length > 0"
        :is="ModelFieldsConfig"
        :model-code="state.selectedKeys[0]"
        :load-model-fun="queryClassifyModels"
      />
      <a-empty v-else :image="simpleImage">
        <template #description>
          <span> 选择左侧模型开始操作 </span>
        </template>
      </a-empty>
    </div>
  </ColPage>
</template>
